import { useLayoutEffect } from 'react';

/**
 * 员工节点的 Tooltip 需求. 因为是 d3 绘制的元素, 无法正常绑定react事件. 所以使用委托的方式来实现.
 * 通过这个 hooks 监听员工列表节点的点击事件, 获取对应参数, 传递给 EmployeeTooltip 组件
 * @param treeId
 * @param tooltipRef
 * @returns {[]}
 */
const useEmployeeListItemCard = (treeId, tooltipRef) => {
    const currentNode = document.querySelector(`#${treeId} .rd3t-tree-container`);

    useLayoutEffect(() => {
        const clickHandle = e => {
            const { target } = e;
            // employeeCode 必须有值, 因为存在没有 "暂无员工" 这样的记录
            const className = target.className?.toString();
            if (className.includes('employeeItemName') && !className.includes('disabled') && target.dataset.employeeCode) {
                tooltipRef.current.show({
                    employeeCode: target.dataset.employeeCode,
                    organizationCode: target.dataset.organizationCode,
                    organizationType: target.dataset.organizationType,
                    organizationPermissions: target.dataset.organizationPermissions
                }, target.getBoundingClientRect());
            }
        };
        if (currentNode) {
            currentNode.addEventListener('mousedown', clickHandle);
        }

        return () => {
            if (currentNode) {
                currentNode.removeEventListener('mousedown', clickHandle);
            }
        };
    }, [currentNode]);

    return [];
};

export default useEmployeeListItemCard;
